/* 
 *  ChatWindowController.m 
 *  iCPU
 *
 *  Created by Kosovan Sasha
 *  Licensed under GNU GPL v2
 *
 * Discovering CPU protocol, i have found misteyks like:
 *  1) selecting with shif up, when size of window is different in oponent sets cursor in wrong position
 *  2) selecting with mouse and then moving arrows will set cursor in wrong position
 */

#import "ChatWindowController.h"
#import "cpu.h"

@implementation ChatWindowController
- (void)textDidChange:(NSNotification *)notification
{
	//NSLog( @"Text Changed!??????");
	[self textChanged];
}

- (void)textDidEndEditing:(NSNotification *)notification {
	// Not needed
	//NSLog( @"textDidEndEditing!");
	

}

- (void)textChanged
{
	if ([[myText textStorage] length])
	inputBuffer[bufferCount] = [[[myText textStorage] string ] characterAtIndex: [[myText textStorage] length] - 1];
	bufferCount ++;
}

- (id)initWithConnection:(NSFileHandle *)aFileHandle 
{
    self = [super initWithWindowNibName:@"ChatWindow"];
    if ( self ) {
		fileHandle = [aFileHandle retain];	
		badCount = 0;
		changeCount = 0;
		bufferCount = 0;
		changedAlot = NO;
		NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
		[nc addObserver:self 
			   selector:@selector(receiveMessage:)
				   name:NSFileHandleReadCompletionNotification
				 object:fileHandle];
		[nc addObserver:self 
			   selector:@selector(closeWindow:)
				   name:NSWindowWillCloseNotification
				 object:[self window]];
		[myText setDelegate: self];
		[nc addObserver:self 
			   selector:@selector(textDidChange:)
				   name:NSTextStorageDidProcessEditingNotification
				 object:myText];
		[fileHandle readInBackgroundAndNotify];
    }
    return self;
}
- (void)closeWindow:(NSNotification *)notification
{
	//NSLog( @"close window");
	[fileHandle closeFile];
	[fileHandle release];
}
- (void)keyUp:(NSEvent *)theEvent
{
	//NSLog([[NSString alloc] initWithFormat:@"Key %@ pressed", [theEvent characters]]);
	struct cpu_packet2 cpu_p1,  cpu_p2;
	BOOL sendSecondPacket = NO;

	//NSLog([[NSString alloc] initWithFormat:@"Key %i, modifier %i",[[theEvent characters] characterAtIndex:0] , [theEvent modifierFlags]]);
	//NSLog([[NSString alloc] initWithFormat:@"Number of characters %i",[[theEvent characters] length] ]);
	
	cpu_p1.msg1 = 0;
	cpu_p1.msg2 = 1;
	cpu_p1.msg3 = 0;
	cpu_p1.msg4 = 0;
	cpu_p2.msg1 = 2;
	cpu_p2.msg2 = 1;
	cpu_p2.msg3 = 0;
	cpu_p2.msg4 = 0;
	cpu_p1.msg6 = 0;
	cpu_p1.msg7 = 0;
	cpu_p1.msg8 = 0;
	cpu_p1.msg9 = 0;
	cpu_p1.msg10 = 0;
	cpu_p1.msg11 = 0;
	cpu_p1.msg12 = 0;
	cpu_p2.msg6 = 0;
	cpu_p2.msg7 = 0;
	cpu_p2.msg8 = 0;
	cpu_p2.msg9 = 0;
	cpu_p2.msg10 = 0;
	cpu_p2.msg11 = 0;
	cpu_p2.msg12 = 0;
	
	if (( [theEvent modifierFlags] & NSShiftKeyMask ) )
	{
		//NSLog( @"shift button");
		cpu_p1.msg0 = 1; cpu_p2.msg0 = 1;
	}else
	if (( [theEvent modifierFlags] & NSControlKeyMask ) )
	{
		cpu_p1.msg0 = 4; cpu_p2.msg0 = 4;
		//NSLog( @"ctrl button");
	}else
	if (( [theEvent modifierFlags] & NSCommandKeyMask  ) )
	{
		cpu_p1.msg0 = 2; cpu_p2.msg0 = 2;
		//NSLog( @"alt button");
	}else
	{
		cpu_p1.msg0 = 0;
		cpu_p2.msg0 = 0;
	};
	
	
/*	if (( [theEvent modifierFlags] & NSLeftArrowFunctionKey ))
	{
		cpu_p1.msg5 = 37;
		//NSLog( @"left button");
	}else
	if (( [theEvent modifierFlags] & NSUpArrowFunctionKey ))
	{
		cpu_p1.msg5 = 38;	
		//NSLog( @"up button");
	}
	if (( [theEvent modifierFlags] & NSRightArrowFunctionKey ))
	{
		cpu_p1.msg5 = 39;
		//NSLog( @"right button");
	}
	if (( [theEvent modifierFlags] & NSDownArrowFunctionKey ))
	{
		cpu_p1.msg5 = 40;
		//NSLog( @"down button");
	}
	if (( [theEvent modifierFlags] & NSPageUpFunctionKey ))
	{
		cpu_p1.msg5 = 33;
		//NSLog( @"pageup button");
	}
	if (( [theEvent modifierFlags] &  NSPageDownFunctionKey ))
	{
		cpu_p1.msg5 = 34;
		//NSLog( @"pageDown button");
	}
	else*/ 
//	changeCount --;
	int i = 0, j;
	j = bufferCount;
	while ( bufferCount > 0) {
		
	if (( [[theEvent characters] characterAtIndex:0] ==  127  ))
	{
		cpu_p1.msg5 = 8; cpu_p2.msg5 = 8;
		sendSecondPacket = YES;
		//NSLog( @"backspace button");
	}
	else
	{
		//cpu_p1.msg5 = [[theEvent characters] characterAtIndex:0];
		//cpu_p2.msg5 = [[theEvent characters] characterAtIndex:0];
		if (i> -1){
		cpu_p1.msg5 = inputBuffer[i] ;
		cpu_p2.msg5 = inputBuffer[i] ;
		}
		
		sendSecondPacket = YES;
		//NSLog( @"key button");
	}
    i++;
	NSString *message =  [[NSString alloc] initWithFormat:@"im sendign %i %i %i %i %i %i %i %i %i %i %i %i %i", 
		cpu_p1.msg0, cpu_p1.msg1, cpu_p1.msg2,cpu_p1.msg3,cpu_p1.msg4,cpu_p1.msg5,cpu_p1.msg6,
		cpu_p1.msg7,cpu_p1.msg8,cpu_p1.msg9,cpu_p1.msg10,cpu_p1.msg11,cpu_p1.msg12];	
	//NSLog(message);
	NSString *message2 =  [[NSString alloc] initWithFormat:@"im sendign %i %i %i %i %i %i %i %i %i %i %i %i %i", 
		cpu_p2.msg0, cpu_p2.msg1, cpu_p2.msg2,cpu_p2.msg3,cpu_p2.msg4,cpu_p2.msg5,cpu_p2.msg6,
		cpu_p2.msg7,cpu_p2.msg8,cpu_p2.msg9,cpu_p2.msg10, cpu_p2.msg11,cpu_p2.msg12];	
	//NSLog(message2);
	
	[fileHandle writeData: [[NSData alloc] initWithBytes:&cpu_p1 length:sizeof(cpu_p1)]];
	if (sendSecondPacket) [fileHandle writeData: [[NSData alloc] initWithBytes:&cpu_p2 length:sizeof(cpu_p2)]];
	bufferCount --;
	}
}

- (void)receiveMessage:(NSNotification *)notification
{
    NSData *messageData = [[notification userInfo] objectForKey:NSFileHandleNotificationDataItem];	
    if ( [messageData length] == 0 ) {
        //[fileHandle readInBackgroundAndNotify];
		if (badCount < 30)
		{
			badCount ++;
			//NSLog( @"bad count ++");	
			//return;
		}
		else
		{
			[fileHandle closeFile];		
			[fileHandle release];
			//NSLog( @"File handle closed");	
			[hisText setBackgroundColor:[NSColor grayColor]]; 
			//[hisText setEditable: YES];
			[hisText setSelectable: YES];
			//[hisText setEditable: NO];
			[myText setEditable: NO];
			[[NSNotificationCenter defaultCenter] removeObserver:self];
			//return;
		}
     	
    }
	
	//NSLog([[NSString alloc] initWithFormat:@"%i	bytes reseived",[messageData length]]);
	[hisText setEditable: YES];
	int gotChar;
	unsigned char aBuffer[2600];
	unsigned char Buffer[13];
	[messageData getBytes:aBuffer];
	int i=0,j=0, length;
	length = [messageData length];
	for ( j=0; j<length; j+=13)
	{
		for ( i=0 ; i<13; i++) 
		{
			Buffer[i]=aBuffer[i+j];
		}
		struct cpu_packet2 *cpu_p;
		(struct cpu_packet2 *)cpu_p = (struct cpu_packet2 *) Buffer;
		NSString *message =  [[NSString alloc] initWithFormat:@"message %i %i %i %i %i %i %i %i %i %i %i %i %i", 
			cpu_p->msg0, cpu_p->msg1, cpu_p->msg2,cpu_p->msg3,cpu_p->msg4,cpu_p->msg5,cpu_p->msg6,
			cpu_p->msg7,cpu_p->msg8,cpu_p->msg9,cpu_p->msg10,cpu_p->msg11,cpu_p->msg12];	
		//NSLog(message);
		//Trying With Mouse;
		if (cpu_p->msg1==177) {
			//5, 9
			//first ==
			//then from left to right
			if (cpu_p->msg5==cpu_p->msg9)
			{
				//[hisText moveToPoint:NSMakePoint(1,1)];  
				[hisText moveToBeginningOfDocument:self];
				int i;
				for (i=0; i< cpu_p->msg5;i++) {
					[hisText moveRight: self];
				}
				//NSLog(@"moving to point");
			}
			else {
				[hisText moveToBeginningOfDocument:self];
				int i;
				for (i=0; i< cpu_p->msg5;i++) {
					[hisText moveRight: self];
				}
				for (i=0; i< cpu_p->msg9 - cpu_p->msg5 ;i++) {
				[hisText moveRightAndModifySelection: self];
				}
				//NSLog(@"moving to point and selecting");
			    }

		}
		else
		if (cpu_p->msg1==2) {
			switch (cpu_p->msg5) {
				case 8:{
						[hisText deleteBackward: self];
						//NSLog(@"backword key");
					    }
				break;
				//case 46:{
				//	[hisText deleteForward:self];
				//	//NSLog(@"delete key");
				//}
					break;
				case 13:{
					[hisText insertNewline: self];
					//NSLog(@"enter key");
				}	
				break;
				
			default:
			{
				gotChar = cpu_p->msg5;
				//NSLog([[NSString alloc] initWithFormat:@"%c",gotChar]);
				[hisText insertText: [[NSString alloc] initWithFormat:@"%c",gotChar]];
			}
				break;
			}
		}	
		else {
			switch (cpu_p->msg5) {
				case 37:{
					if (cpu_p->msg0==1) {
						[hisText moveLeftAndModifySelection:self];
						//NSLog(@"shift+left key");
						break;
					};
					[hisText moveLeft:self];
					//NSLog(@"left key");
				}	
					break;
				case 46:
					[hisText deleteForward:self];
					//NSLog(@"delete key");
					break;
				case 38:{
					if (cpu_p->msg0==1) {
						[hisText moveUpAndModifySelection:self];
						//NSLog(@"shift+up key");
						break;
					};
					[hisText moveUp: self];
					//NSLog(@"up key");
				}	
					break;
				case 39:{
					if (cpu_p->msg0) {
						[hisText moveRightAndModifySelection:self];
						//NSLog(@"shift+right key");
						break;
					}
					[hisText moveRight:self];
					//NSLog(@"right key");
				}	
					break;
				case 40:{
					if (cpu_p->msg0) {
						[hisText moveDownAndModifySelection:self];
						//NSLog(@"shift+down key");
						break;
					}
					[hisText moveDown: self];
					//NSLog(@"down key");
				}	
					break;
			}
		}

	}
	
	//5, 15
	////NSLog([NSString stringWithCString:80 encoding:NSASCIIStringEncoding]);
	[hisText setEditable: NO];
	[hisText setSelectable: NO];
	[fileHandle readInBackgroundAndNotify];
}
@end
